package com.yinhe.music.yhmusic.downmanager;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.umeng.analytics.MobclickAgent;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.DownloadMusicEntity;
import com.yinhe.music.yhmusic.utils.MusicUtils;
import com.yinhe.music.yhmusic.widget.SmoothCheckBox;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hasee on 2017/5/22.
 */

public class DownLoadManagerActivity extends BaseServiceActivity {
    private TextView delete;
    private List<DownloadMusicEntity> mDownMusic = new ArrayList<>();
    private DownAdapter mAdapter;
    private List<Integer> mSelectMusic = new ArrayList<>();
    private boolean isSelect;

    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    @Override
    public void initView() {
        RxBus.get().register(this);
        TextView down = findViewById(R.id.down);
        TextView play = findViewById(R.id.play);
        TextView add = findViewById(R.id.add_to);
        delete = findViewById(R.id.delete);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        add.setVisibility(View.GONE);
        down.setVisibility(View.GONE);
        play.setVisibility(View.GONE);
        mAdapter = new DownAdapter(null);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

        setToolbar("批量操作");
        showQuickControl(true);
        updateData();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_manage;
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_select, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_all) {
            if (isSelect) {
                isSelect = false;
                item.setTitle("全选");
            } else {
                isSelect = true;
                item.setTitle("取消全选");
            }
            mAdapter.updateSelect(isSelect);
        }
        return super.onOptionsItemSelected(item);
    }

    public class DownAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private List<DownloadMusicEntity> mList;

        DownAdapter(List<DownloadMusicEntity> list) {
            mList = list;
        }

        public void update(List<DownloadMusicEntity> list) {
            mList = list;
            notifyDataSetChanged();
        }

        private void updateSelect(boolean check) {
            for (DownloadMusicEntity i : mList) {
                i.setIs_select(check);
            }
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            return new ItemView(layoutInflater.inflate(R.layout.select_item, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
            final DownloadMusicEntity musicEntity = mList.get(position);
            ((ItemView) holder).cb.setOnCheckedChangeListener((checkBox, isChecked) ->
                    musicEntity.setIs_select(isChecked)
            );

//            switch (musicEntity.getQtype()) {
//                case IConstants.Common:
//                    ((ItemView) holder).img.setImageResource(R.drawable.ic_regular);
//                    break;
//                case IConstants.HQ:
//                    ((ItemView) holder).img.setImageResource(R.drawable.ic_hq);
//                    break;
//                case IConstants.SQ:
//                    ((ItemView) holder).img.setImageResource(R.drawable.ic_sq);
//                    break;
//                default:
//                    break;
//            }
            ((ItemView) holder).cb.setChecked(musicEntity.is_select);
            ((ItemView) holder).tv.setText(musicEntity.getSongname());
            ((ItemView) holder).itemView.setOnClickListener(v -> {
                musicEntity.setIs_select(!musicEntity.is_select);
                ((ItemView) holder).cb.setChecked(musicEntity.is_select, true);
            });

            delete.setOnClickListener(v -> {
                for (DownloadMusicEntity i : mList) {
                    if (i.is_select) {
                        mSelectMusic.add((int) i.songid);
                    }
                }
                if (mSelectMusic.size() > 0) {
                    MobclickAgent.onEvent(DownLoadManagerActivity.this, "batch_delete");
                    DataBaseAccessor.getInstance().deleteDownMusicByList(mSelectMusic, false);
                } else {
                    Toast.makeText(getApplicationContext(), "请选择要删除的任务", Toast.LENGTH_SHORT).show();
                }

            });
        }

        @Override
        public int getItemCount() {
            return mList != null ? mList.size() : 0;
        }

        private class ItemView extends RecyclerView.ViewHolder {
            private SmoothCheckBox cb;
            private TextView tv;
//            private ImageView img;

            ItemView(View itemView) {
                super(itemView);
                cb = itemView.findViewById(R.id.scb);
                tv = itemView.findViewById(R.id.tv);
//                img = itemView.findViewById(R.id.img);
            }
        }
    }

    private void updateData() {
        List<DownloadMusicEntity> data = DataBaseAccessor.getInstance().getDowningMusic();
        if (data != null) {
            mDownMusic = data;
            mAdapter.update(mDownMusic);
        }
    }

    private DownloadMusicEntity removeMusicByID(long id) {
        if (mDownMusic == null || mDownMusic.size() == 0) {
            return null;
        }
        int index = 0;
        for (DownloadMusicEntity i : mDownMusic) {
            if (i.getSongid() == id) {
                return mDownMusic.remove(index);
            }
            index++;
        }
        return null;
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC)})
    public void onRxbusDeleteDownMusicByList(RxbusListObject rxbusListObject) {
        if (rxbusListObject.rxList != null) {
            for (Object i : rxbusListObject.rxList) {
                Integer taskId = (Integer) i;
                DownloadMusicEntity tmp = removeMusicByID(taskId);
                if (mService != null && tmp != null) {
                    mService.cancelDownloadTask(taskId);
                    MusicUtils.deleteFile(this, tmp);
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }
}
